package cn.regexp.elasticjob.config;

import cn.regexp.elasticjob.job.FileCustomElasticJob;
import cn.regexp.elasticjob.job.MyElasticJob;
import cn.regexp.elasticjob.mapper.FileCustomMapper;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
public class ElasticJobConfig {

    @Autowired
    private MyElasticJob myElasticJob;
    @Autowired
    private CoordinatorRegistryCenter registryCenter;

    /**
     * 初始化简单 ElasticJob
     * @return 基于Spring的作业启动器
     */
    @Bean(initMethod = "init")  // 在初始化调用该实例方法
    public SpringJobScheduler initSimpleElasticJob(FileCustomElasticJob fileCustomElasticJob) {
        return new SpringJobScheduler(fileCustomElasticJob, registryCenter,
                createJobConfiguration(FileCustomElasticJob.class.getCanonicalName(),
                "0/3 * * * * ?", 4, "0=text,1=vedio,2=image,3=radio"));
    }

    /*@Bean(initMethod = "init")  // 在初始化调用该实例方法
    public SpringJobScheduler initSimpleElasticJob() {
        return new SpringJobScheduler(myElasticJob, registryCenter,
                createJobConfiguration(MyElasticJob.class.getCanonicalName(),
                        "0/3 * * * * ?", 1, null));
    }*/

    /**
     *
     * @param jobName 作业名称
     * @param cron  作业启动时间的 cron 表达式
     * @param shardingTotalCount    作业分片总数
     * @param shardingItemParameters
     * @return Lite 作业配置
     */
    private LiteJobConfiguration createJobConfiguration(String jobName,
                                                        String cron,
                                                        int shardingTotalCount,
                                                        String shardingItemParameters) {
        // 定义作业核心配置
        JobCoreConfiguration.Builder coreConfiguration = JobCoreConfiguration
                .newBuilder(jobName, cron, shardingTotalCount);

        if(!StringUtils.isEmpty(shardingItemParameters)){
            coreConfiguration.shardingItemParameters(shardingItemParameters);
        }
        // 定义简单任务配置
        SimpleJobConfiguration simpleJobConfiguration = new SimpleJobConfiguration(coreConfiguration.build(), jobName);
        // 定义 Lite 作业配置
        return LiteJobConfiguration.newBuilder(simpleJobConfiguration).overwrite(true).build();
    }

}
